# -*- coding:utf-8 -*-
import time
import re
import MySQLdb

host = "127.0.0.1"
user = "root"
password = "root"
port = 3306
database = "mryx"


def execSql(sql):
    try:
        conn = MySQLdb.connect(host=host, user=user, password=password, port=port, database=database, charset='utf8')
        cur = conn.cursor()
        cur.execute(sql)
        conn.commit()
        return True
    except Exception:
        pass
    return False


def querySql(sql):
    try:
        conn = MySQLdb.connect(host=host, user=user, password=password, port=port, database=database, charset='utf8')
        cur = conn.cursor()
        cur.execute(sql)
        return cur.fetchall()
    except Exception:
        pass
    return


def getAttrs(detailText, key):
    try:
        for d in detailText:
            try:
                if key in d['name']:
                    return d['text']
            except Exception:
                pass
    except Exception:
        return ""


def getCurrentTime():
    return str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))


def checkGoodsExists(sku):
    try:
        sql = "select * from mryx_goods_list where goods_id = '%s'" % str(sku)
        return len(querySql(sql)) > 0
    except Exception:
        return False


def addGoods(data):
    try:
        print("数据新增, 操作一级类目：%s, 操作二级类目：%s, 商品名称：%s, 操作时间：%s !" %
              (data['fs_category_name'], data['sec_category_name'], data['goods_name'], getCurrentTime()))
        sql = "insert mryx_goods_list(`goods_id`, `fs_category_name`, `sec_category_name`, `goods_name`, " \
              "`goods_desc`, `price`, `ge_place`, `attr`, `weight`, `comment_nums`, " \
              "`sell_nums`) values('%s', '%s', '%s', '%s', '%s', %f, '%s', '%s', '%s', '%s', '%s')" % (
                data['goods_id'], data['fs_category_name'], data['sec_category_name'], data['goods_name'],
                data['goods_desc'], data['price'], data['ge_place'], data['attr'], data['weight'], data['comment_nums'],
                data['sell_nums']
                )
        execSql(sql)
    except Exception:
        pass


def updateGoods(data):
    try:
        print("数据更新, 操作一级类目：%s, 操作二级类目：%s, 商品名称：%s, 操作时间：%s !" %
              (data['fs_category_name'], data['sec_category_name'], data['goods_name'], getCurrentTime()))
        sql = "update mryx_goods_list set `price` = %f, `ge_place` = '%s', `attr` = '%s', " \
              "`weight` = '%s', `comment_nums` = '%s', `sell_nums` = '%s' where `goods_id` = '%s'" % (
                data['price'], data['ge_place'], data['attr'], data['weight'], data['comment_nums'],
                data['sell_nums'], data['goods_id']
                )
        execSql(sql)
    except Exception:
        pass


def getSellNum(saleText):
    try:
        pat = re.compile("\\d+")
        return str(int(re.findall(pat, saleText)[0]))
    except Exception:
        return ""


def getGoodsDetail(resp, fsCaName, secCaName, commentNum):
    try:
        datas = resp['data']['productInfo']
        datass = resp['data']['productDetail']
        goods = dict()
        goods['goods_id'] = datas['sku']
        goods['fs_category_name'] = fsCaName
        goods['sec_category_name'] = secCaName
        goods['goods_name'] = datas['title']
        try:
            goods['goods_desc'] = datas['subTitle']
        except Exception:
            goods['goods_desc'] = ""
        goods['price'] = float("%.2f" % (float(datas['pricePro']['noVip']['price']) / 100))
        goods['ge_place'] = getAttrs(datass['detailText'], "产地")
        goods['attr'] = getAttrs(datass['detailText'], "规格")
        goods['weight'] = getAttrs(datass['detailText'], "重量")
        goods['comment_nums'] = commentNum
        try:
            goods['sell_nums'] = getSellNum(datas['saleInfo']['text'])
        except Exception:
            goods['sell_nums'] = ""
        return goods
    except Exception:
        pass


def parser(respData, fsCaName, secCaName, commentNum):
    goods = getGoodsDetail(respData, fsCaName, secCaName, commentNum)
    if goods is not None and len(goods) > 0:
        exists = checkGoodsExists(goods['goods_id'])
        if not exists:
            addGoods(goods)
        else:
            updateGoods(goods)
        return True
    return False
